package priv.utrix.micro.converter;

import com.google.common.collect.Maps;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import priv.utrix.micro.dto.SecurityUserDto;

import java.util.Map;

import static priv.utrix.micro.constant.UserMapKeyConstants.*;

/**
 * 自定义Token增强
 *
 * @author utrix
 * @date 2020/11/23
 */
public class CustomJwtTokenConverter extends JwtAccessTokenConverter {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        SecurityUserDto principal = (SecurityUserDto) authentication.getUserAuthentication().getPrincipal();
        // 往token中添加自定义信息
        final Map<String, Object> additionalInformation = Maps.newHashMapWithExpectedSize(3);
        additionalInformation.put(USER_ID, principal.getId());
        // 手动添加，目的是为了获取用户名，生成redis key
        additionalInformation.put(USERNAME, principal.getUsername());
        additionalInformation.put(AUTHORITY_CODE_LIST, principal.getAuthorityCodeList());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
        return super.enhance(accessToken, authentication);
    }
}
